#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

struct Edge
{
    int a, b, w;
    bool operator< (const Edge& W)const{
        return w < W.w;
    }
};

const int N = 6010;

int n;
Edge edge[N];
int p[N], s[N];

int find(int x){
    if(x != p[x]){
        p[x] = find(p[x]);
    }

    return p[x];
}

void init(){
    for(int i = 1; i <= n; i ++){
        p[i] = i;
    }

    for(int i = 1; i <= n; i ++){
        s[i] = 1;
    }

}

void solve(){
    int res = 0;

    scanf("%d", &n);
    init();
    
    for(int i = 0; i < n - 1; i ++){
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        edge[i] = {x, y, z};
    }

    sort(edge, edge + n - 1);

    for(int i = 0; i < n - 1; i ++){
        int x = edge[i].a, y = edge[i].b, z = edge[i].w;

        int a = find(x), b = find(y);
        if(a != b){
            res += (s[a] * s[b] - 1) * (z + 1);
            p[a] = p[b];
            s[b] += s[a];
        }
    }

    printf("%d\n",  res);
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    int T;
    scanf("%d", &T);
    while(T--){
        solve();
    }

    return 0;
}